var express = require('express');
var path = require('path');
var fs = require('fs');
let mysqlExec = require('../db/dbMySql.js');
let { Msg, curPath, createJWT, useJWT } = require('../tools/msg.js');
const { v4: uuidv4 } = require('uuid');
var svgCaptcha = require('svg-captcha');
const formidable = require('formidable');
//引入md5包用来加密密码
var md5 = require('md5');
var router = express.Router();

//修改用户头像：
router.post('/userlogo', async(req, res) => {
    //获取jwt数据(从ajax请求头信息中获取jwt数据)
    let jwtdata = req.headers.authorization;
    //使用jwt数据：
    let jwtObj = useJWT(jwtdata);
    if (!jwtObj) {
        res.send(Msg(500, '非法访问'));
        return;
    }

    let curPaths = path.join(__dirname, '../uploads/avatar');

    //判断文件或目录是否存在：
    if (!fs.existsSync(curPaths)) { //uploads目录不存在时则创建该目录
        //创建目录：
        fs.mkdirSync(curPaths);
    }

    const form = formidable({ multiples: true, uploadDir: curPaths });
    //form.parse()：用来处理含有文件上传的表单
    form.parse(req, async(err, fields, files) => {

        if (err) { //含有文件上传的表单处理失败
            res.send('文件上传失败');
        } else { //含有文件上传的表单处理成功

            //要上传的原始文件名
            let fileNames = files.logo.name;
            let fArr = fileNames.split('.');
            //获取文件扩展名:
            let extName = fArr[fArr.length - 1];
            //完整文件名：
            let fullname = `${uuidv4()}.${extName}`;



            //将上传成功后的临时文件重命名成正式文件名：
            fs.renameSync(files.logo.path, `${curPaths}/${fullname}`);

            let sql = `update e_member set head_photo_url='avatar/${fullname}' where mid='${jwtObj.uid}'`;
            let [e, d] = await mysqlExec(sql);
            if (e) {
                res.send(Msg(200, '用户头像上传成功', `${curPath}avatar/${fullname}`));
            } else {
                res.send(Msg(500, '用户头像上传失败'));
            }

        };
    })
});

//我的课程的接口：
router.post('/mycourse', async(req, res) => {
    //获取JWT数据：
    let { jwtdata = '' } = req.body;
    if (jwtdata == '') {
        res.send(Msg(500, '非法访问'));
        return
    }

    //使用jwt数据：
    let jwtObj = useJWT(jwtdata);
    if (!jwtObj) {
        res.send(Msg(500, '非法访问'));
        return
    }

    //查询我的课程
    let sql = `select o.cid,title,concat('${curPath}course/',image_src) as image_src,
    area_name,subject_name ,price from  e_order as o inner join e_course as c 
    on o.cid=c.cid where mid='${jwtObj.uid}'`;
    let [err, data] = await mysqlExec(sql);
    if (err) {
        res.send(Msg(200, '我的课程查询成功', data));
    } else {
        res.send(Msg(500, '我的课程查询失败'));
    }

});

module.exports = router;